package com.zmjmall.demo.async;

import com.alibaba.fastjson.JSON;
import com.zmjmall.demo.api.UserService;
import com.zmjmall.demo.model.User;
import com.zmjmall.demo.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.Future;

/**
 * 异步更新
 *
 * @author zmj
 * @version 2018/7/5
 */
@Component
@Slf4j
public class AsyncTask {

    @Autowired
    private UserService userService;

    /**
     * 登录信息异步更新
     * @param request
     * @param redisInfo
     * @return
     */
    @Async
    public Future<Boolean> doLoin(HttpServletRequest request,String redisInfo) {

        String ip = IpUtil.getIpAddr(request);

        User user = JSON.parseObject(redisInfo, User.class);
        log.info("[用户登录] 用户：{}，登录ip: {}",user.getPhone(),ip);
        user.setLoginType(1);
        if(IpUtil.isMobileDevice(request.getHeader("user-agent"))) {
            user.setLoginType(2);
        }
        userService.updateLoginInfo(user);
        log.info("执行异步方法。。。更新登录信息");
        return new AsyncResult<>(true);
    }
}
